/**
 * 
 */
package info.niwota.search;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

/**
 * @author qiangli
 * 
 */
public class CryptUtils {
	private static final int KEYSIZE = 1024;
	private static final String UTF8 = "UTF-8";

	public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
		kpg.initialize(KEYSIZE);
		KeyPair kp = kpg.generateKeyPair();
		return kp;
	}

	public static String decrypt(KeyPair kp, String ciphertext)
			throws Exception {
		Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		c.init(Cipher.DECRYPT_MODE, kp.getPrivate());
		byte[] d = Base64.decode(ciphertext);
		byte[] b = c.doFinal(d);
		return new String(b, UTF8);
	}

	public static String[] toPublicKey(KeyPair kp) {
		String[] keys = new String[2];
		RSAPublicKey pk = (RSAPublicKey) kp.getPublic();
		keys[0] = pk.getModulus().toString(16);
		keys[1] = pk.getPublicExponent().toString(16);
		return keys;
	}

	public static Key generateKey() throws NoSuchAlgorithmException {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128);
		Key key = kgen.generateKey();
		return key;
	}

	public static String encrypt(Key key, String cleartext) throws Exception {
		Cipher c = Cipher.getInstance("AES");
		c.init(Cipher.ENCRYPT_MODE, key);
		byte[] b = cleartext.getBytes(UTF8);
		byte[] d = c.doFinal(b);
		return Base64.encodeBytes(d);
	}

	public static String decrypt(Key key, String ciphertext) throws Exception {
		if (isEmpty(ciphertext)) {
			return ciphertext;
		}
		Cipher c = Cipher.getInstance("AES");
		c.init(Cipher.DECRYPT_MODE, key);
		byte[] d = Base64.decode(ciphertext);
		byte[] b = c.doFinal(d);
		String dec = new String(b, UTF8);
		return dec;
	}

	private static boolean isEmpty(String s) {
		return s == null || s.equals("");
	}
}
